<template>
  <q-field ref="QColors" v-model="RGBA" :autogrow="false" :class="fieldCls" :clearable="clearable" :disable="disable"
           :error="!isValid" :error-message="placeholder" :readonly="readonly" class="q-field__text"
           lazy-rules="ondemand" v-bind="$attrs" @clear="handleClear" @focus="fieldFocus">
    <template v-slot:control>
      <span v-if="!RGBA" class="placeholder">{{ placeholder }}</span>
      <QxTooltip v-else>{{ RGBA }}</QxTooltip>
    </template>
    <template v-slot:append>
      <q-icon name="color_lens"></q-icon>
    </template>
    <q-popup-proxy v-model="showPopup" :no-parent-event="readonly || disable" :offset="[0, 5]" anchor="bottom left"
                   breakpoint="0" class="" no-refocus self="top left" transition-hide="jump-up"
                   transition-show="jump-down" @hide="popupBlur">
      <q-color v-model="RGBA" format-model="rgba" no-header></q-color>
    </q-popup-proxy>
  </q-field>
</template>

<script setup>
import QxTooltip from 'components/Global/Tools/QxTooltip.vue'
import { computed, nextTick, onBeforeUnmount, onMounted, ref, watchPostEffect } from 'vue'

const props = defineProps({
  type: String, clearable: Boolean, placeholder: String, option: [Array, Function], lazyRules: [Boolean, String],
  modelValue: String, disable: Boolean, readonly: Boolean
})
const emits = defineEmits(['change', 'update:modelValue'])

const RGBA = ref('')
const QColors = ref(null)
const isValid = ref(true)
const showPopup = ref(false)

const fieldCls = computed(() => showPopup.value ? 'q-field--focused q-field--highlighted' : '')
watchPostEffect(() => (RGBA.value = props.modelValue || ''))

const handleClear = () => {
  RGBA.value = void 0
  showPopup.value = false
  popupBlur()
}
const popupBlur = () => {
  emits('change', RGBA.value)
  emits('update:modelValue', RGBA.value)
  if (props.lazyRules === 'ondemand') return
  nextTick(() => {
    if (!QColors.value) return
    QColors.value.blur()
    isValid.value = QColors.value.validate()
  })
}
const fieldFocus = () => {
  // showPopup.value = !showPopup.value
}

const scrollHandle = () => {
  if (!showPopup.value || !QColors.value) return
  const offset = QColors.value.$el.getBoundingClientRect()
  const innerHeight = window.innerHeight
  if (offset.top > innerHeight || offset.bottom < 0) showPopup.value = false
}
const resizeHandle = () => showPopup.value = false
onMounted(() => {
  window.addEventListener('scroll', scrollHandle, true)
  window.addEventListener('resize', resizeHandle, false)
})
onBeforeUnmount(() => {
  window.removeEventListener('scroll', scrollHandle, true)
  window.removeEventListener('resize', resizeHandle, false)
})

</script>